<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    :destroy-on-close="true"
    @close="closeDialog"
  >
    <CommonForm
      :formConfig="formConfig"
      ref="formRef"
      :inline="true"
      :cols="2"
      :labelWidth="125"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";

defineOptions({
  name: "AddOrganization",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible", "get-type-list"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  parentId: {
    type: String,
    default: () => {
      return "";
    },
  },
});

/**
 * 初始化 config
 */
const createFormConfig = [
  {
    type: "input", // 普通输入框
    inputType: "text", // 类型, text/textarea
    label: "组织机构名称", // 标签文本
    fieldName: "organizationName", // 字段名称
    placeholder: "请输入组织机构名称", // 提示文字
    initValue: "", // 默认值
    rules: [
      {
        required: true,
        message: "请输入组织机构名称",
        trigger: "blur",
      },
      {
        required: true,
        message: "不能超过45个字符",
        max: 45,
      },
    ],
  },
  {
    type: "input",
    inputType: "text",
    label: "编码",
    fieldName: "organizationCode",
    placeholder: "请输编码",
    initValue: "",
    rules: [
      { required: true, message: "请输入编码", trigger: "blur" },
      {
        required: true,
        message: "不能超过45个字符",
        max: 45,
      },
    ],
  },
  {
    type: "input",
    inputType: "text",
    label: "统一社会信用代码",
    maxlength: 250,
    showWordLimit: true,
    fieldName: "uscc",
    placeholder: "请输入统一社会信用代码",
    initValue: "",
  },
  {
    type: "select",
    label: "类型",
    fieldName: "organizationType",
    placeholder: "请选择类型",
    initValue: "3",
    defaultFirstOption: true,
    rules: [{ required: true, message: "请输入选择类型", trigger: "change" }],
    optionList: [],
  },
  {
    type: "select",
    label: "负责人",
    fieldName: "chargeManagerId",
    placeholder: "请选择",
    initValue: "",
    defaultFirstOption: true,
    optionList: [],
  },
  {
    type: "select",
    label: "是否是国内企业",
    fieldName: "internal",
    placeholder: "请选择",
    initValue: "",
    defaultFirstOption: true,
    optionList: [],
  },
  {
    type: "date",
    label: "加入年份",
    fieldName: "addYear",
    placeholder: "加入年份",
    startPlaceholder: "", // 范围选择时开始日期的占位内容
    endPlaceholder: "", // 范围选择时结束日期的占位内容
    initValue: "",
    dataType: "year", // 	year(年-YYYY)/month(月-YYYY-MM)/date(日-YYYY-MM-DD)/dates(多日期选择)/datetime(日期时间-YYYY-MM-DD hh:mm:ss)/ week(周-ww 周)/datetimerange(日期时间段-YYYY-MM-DD hh:mm:ss)/daterange(日期段-YYYY-MM-DD)/ monthrange(月份范围-YYYY-MM)
    valueFormat: "YYYY", // 日期格式默认年月日
    disabled: false, // 是否禁用

    change: () => {},
  },
  {
    type: "input",
    inputType: "textarea",
    label: "简介",
    rows: 2,
    maxlength: 250,
    showWordLimit: true,
    fieldName: "remarks",
    placeholder: "请输入简介",
    initValue: "",
  },
  {
    type: "input",
    inputType: "textarea",
    label: "地址",
    maxlength: 250,
    showWordLimit: true,
    fieldName: "addresss",
    rows: 2,
    placeholder: "请输入地址",
    initValue: "",
  },
  {
    type: "input",
    inputType: "textarea",
    rows: 2,
    maxlength: 250,
    showWordLimit: true,
    label: "组织机构描述",
    fieldName: "organizationDescription",
    placeholder: "请输入组织机构描述",
    initValue: "",
  },
  {
    type: "inputNumberBtn",
    label: "排序",
    fieldName: "sort",
    placeholder: "排序",
    initValue: 0,
    style: "width: 200px !important;",
    DisableInput: "e,+,-,Shift,.", // 禁止输入的值，默认值e,+,-,Shift
    change: () => {},
  },
];

/**
 * 全局表单参数
 */
const formConfig: any = ref(createFormConfig);
const formRef = ref();
const id = ref("");

function handleEchoForm(user: any) {
  let params = ["id"];
  createFormConfig.map((item) => {
    params.push(item.fieldName);
  });
  params.map((item) => {
    formRef.value.set(item, user[item]);
  });
  formRef.value.set("addYear", user["addYear"].toString());
  formRef.value.set("internal", user["internal"].toString());
  formRef.value.set("organizationType", user["organizationType"].toString());
}

/** 字典接口及数据处理 */
function getDictData(id: string) {
  return new Promise(async (resolve) => {
    const { data } = await request({
      url: `/system/Dictionary/getSelectedItems/${id}`,
      method: "post",
    });
    resolve(data);
  });
}

function handleDictData(type: string, list: any) {
  let typeIndex = 0;
  createFormConfig.map((item: any, index: number) => {
    if (item.fieldName === type) {
      typeIndex = index;
    }
  });
  createFormConfig[typeIndex].optionList = list;
}

/** 弹窗显示隐藏 */
const visibleDialog = ref(false);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** 检测数据的变化 */
watch(
  () => props.data,
  (newVal) => {
    id.value = "";
    console.log("清空", id.value);
    if (newVal.id) {
      id.value = newVal.id;
      handleEchoForm(newVal);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  formConfig.value = createFormConfig;
}

/** 保存提交 */
const loading = ref(false);

function handleSubmit() {
  formRef.value.validate().then(async (res: any) => {
    loading.value = true;
    const text = id.value ? "编辑" : "新增";
    console.log(id.value && !props.parentId ? "编辑" : "新增", res);
    const params =
      id.value && !props.parentId
        ? {
            ...props.data,
            ...res,
            internal: res.internal,
            addYear: res.addYear ?? "",
          }
        : {
            ...res,
            id: "",
            internal: res.internal,
            addYear: res.addYear ?? "",
            parentId: props.parentId,
          };
    await request({
      url: "/system/sysOrganization/save",
      method: "post",
      data: params,
    }).finally(() => {
      loading.value = false;
    });
    ElMessage.success(`${text}成功`);
    closeDialog();
    emit("reset-table");
  });
}

/** 初始化字典数据 */
onMounted(async () => {
  handleDictData("organizationType", await getDictData("OrganizationType"));
  handleDictData("internal", await getDictData("OrganizationInternal"));
  const typeList = await getDictData("OrganizationType");
  handleDictData("organizationType", typeList);
  getusers();
  emit("get-type-list", typeList);
});

async function getusers() {
  const { data } = await request({
    url: "/system/sysUser/getusers",
    method: "post",
    data: {},
  });
  await handleDictData("chargeManagerId", data);
  return data;
}

// 组件销毁时调用
onBeforeUnmount(() => {
  closeDialog();
});
</script>

<style lang="scss" scoped>
:deep(input[type="number"]) {
  text-align: center;
}
</style>
